<template>
  <view class="content">
    <view class="upload-wrapper">
      <view class="upload-btn-container" @tap="chooseFile">
        <uni-icons type="plus" size="22" color="#666"></uni-icons>
      </view>

      <!-- 上传进度条 -->
      <view class="progress-container" v-if="isUploading">
        <view class="progress-bar">
          <view class="progress-fill" :style="{ width: uploadProgress + '%' }"></view>
        </view>
        <text class="progress-text">{{ uploadProgress }}%</text>
      </view>

      <!-- 文件列表 -->
      <view class="file-list-container" v-if="fileList.length > 0">
        <view class="file-item" v-for="(file, index) in fileList" :key="index">
          <view class="file-info" @click="ImgviewClick(fileList, file)">
            <text class="file-icon">🖼️</text>
            <text class="file-name">{{ truncateMiddle(file.name) }}</text>
          </view>
          <view class="delete-btn" @tap="deleteFile(file, index)">
            <up-icon name="close-circle-fill" size="20" color="#ff4d4f"></up-icon>
          </view>
        </view>
      </view>
    </view>

    <modalindex ref="modalindex" :modalTitle="modalTitle" :modalPlaceholder="modalPlaceholder"
      :Doyouwanttoinput="Doyouwanttoinput" @handleModalConfirm="handleModalConfirm"></modalindex>
  </view>
</template>

<script>
import apply from "@/apis/cloud/apply.js"
import { COMMON_API_BASE_URL } from '@/utils/request'
import { useUserStore } from '@/pinia-store/user'
import { mapStores } from 'pinia'
import modalindex from '@/components/Operationboxpublic/modalindex.vue'
import { ProcessingURL, ImgviewClick } from '@/utils/publicmethod.js'
export default {
  name: 'QrCodePhotoUpload',
  components: {
    modalindex
  },
  props: {
    formData: {
      type: Object,
      default: () => [],
    },
    ApplyDetailList: {
      type: Array,
      default: () => []
    },
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    placeholder: {
      type: String,
      default: '请选择图片'
    },
    maxSize: {
      type: Number,
      default: 5
    },
    maxNumber: {
      type: Number,
      default: 10
    },
    enableZip: {
      type: Boolean,
      default: true
    },
    itemIndex: {
      type: Number,
      default: 0
    },
    format: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: null
    },
    itemId: {
      type: String,
      required: true
    },
    propsitem: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  watch: {
    fileList: {
      handler (newValue) {
        let value = uni.getStorageSync('formData');
        let formItems = JSON.parse(value.formItems);
        formItems.forEach(item => {
          if (item.title == this.title) {
            // item.value.push(...this.fileList);
            uni.setStorageSync(item.id, this.fileList || newValue);
          }
        })
      },
      deep: true,
    }
  },
  data () {
    return {
      uploadUrl: `${COMMON_API_BASE_URL}/dist/interface/public/index.php/form/QrCode/uploadPhoto`,
      isUploading: false,
      uploadProgress: 0,
      fileList: [],
      formats: ['docx', 'doc', 'pdf', 'jpeg', 'jpg', 'png', 'gif', 'ppt', 'pptx', 'xls', 'xlsx'],
      sizeLimit: 30, // MB
      countLimit: 8,
      nextCloud: {},
      uploadOptions: {},
      token: '',
      component_id: '',
      modalTitle: '',
      modalPlaceholder: '',
      Doyouwanttoinput: false,
    }
  },
  computed: {
    ...mapStores(useUserStore)
  },
  created () {
    let that = this
    uni.$on('onUnloadupdateMileagePhoto', function (data) {
      that.onUnloadupdateMileagePhoto()
    })

    uni.$on('updateMileagePhoto', async function (data) {
      let imgurl
      imgurl = data.imgurl
      // #ifdef H5
      imgurl = await that.base64ToTempFilePath(data.imgurl)
      // #endif

      if (that.itemId === data.itemId) {
        that.setapplyUploadPhoto(imgurl, data.itemId)
      }
    })

    this.token = this.userStore.user.token;
    this.setechodata()
  },
  methods: {
    onUnloadupdateMileagePhoto () {
      console.log('调到了销毁');
      uni.$off('updateMileagePhoto');
      uni.$off('onUnloadupdateMileagePhoto');
    },
    setechodata () {
      // 添加数据回显逻辑
      if (this.ApplyDetailList && this.ApplyDetailList.formData && this.itemId) {
        // 检查 formData 中是否存在当前 itemId 对应的字段 
        if (this.ApplyDetailList.formData.hasOwnProperty(this.itemId)) {
          // 获取对应的值
          const fieldValue = this.ApplyDetailList.formData[this.itemId];

          // 如果值是数组，取第一个元素（根据你的数据结构）
          if (Array.isArray(fieldValue) && fieldValue.length > 0) {
            this.fileList = fieldValue
          } else {
            // 直接赋值 
            this.fileList = fieldValue || [];
          }
        }
      }
    },
    truncateMiddle (text, maxLength = 20) {
      if (text.length <= maxLength) return text;
      const half = Math.floor(maxLength / 2.5);
      return `${text.slice(0, half)}...${text.slice(-half)}`;
    },
    async setapplyUploadPhoto (url, id) {
      let that = this
      uni.showLoading({ title: '上传中...', mask: true });

      try {
        let res = await apply.applyGenerateToken({
          component_id: id,
          token: that.token,
        })

        if (res.status == 1) {
          uni.uploadFile({
            url: this.uploadUrl,
            filePath: url,
            name: 'file',
            formData: {
              'token': that.token,
              component_id: id || '',
              qrToken: res.data.qrToken,
              apply_id: this.formData?.id || ''
            },
            success: (resdata) => {
              uni.hideLoading();
              let data = JSON.parse(resdata.data)
              if (data.status == 1) {
                if (that.itemId == id) {
                  that.fileList.push(data.data)
                }

                uni.showToast({
                  title: data.msg || '上传成功',
                  icon: 'success',
                  duration: 2000
                })
              } else {
                uni.showToast({
                  title: data.msg || '上传失败，请稍后重试',
                  icon: 'none',
                  duration: 1000
                });
              }
            },
            fail: () => {
              uni.showToast({
                title: data.msg || '上传失败，请稍后重试',
                icon: 'none',
                duration: 1000
              });
              uni.hideLoading();
            }
          });
        } else {
          uni.showToast({
            title: res.msg || '上传失败，请稍后重试',
            icon: 'none',
            duration: 1000
          });
        }
      } catch (error) {
        uni.hideLoading();
      }
    },
    chooseFile () {
      const remaining = this.countLimit - this.fileList.length
      if (remaining <= 0) {
        uni.showToast({
          title: `最多可上传${this.countLimit}个文件`,
          icon: 'none'
        })
        return
      }

      // #ifdef APP-PLUS
      uni.navigateTo({
        url: `/pages/watermark/components/home?source=QrCodePhotoUpload&id=${this.formData.id}&itemId=${this.itemId}`,
        animationType: 'none'
      });
      // #endif

      // #ifdef H5
      uni.navigateTo({
        url: `/pages/watermark/components/h5camera?source=QrCodePhotoUpload&id=${this.formData.id}&itemId=${this.itemId}`,
        animationType: 'none'
      });
      // #endif
    },
    deleteFile (file, index) {
      this.modalTitle = `确定删除吗？`
      this.Doyouwanttoinput = false
      this.$refs.modalindex.open(file, index)
    },
    base64ToTempFilePath (base64Data) {
      const base64WithoutPrefix = base64Data.replace(/^data:image\/\w+;base64,/, '');
      const byteCharacters = atob(base64WithoutPrefix);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: 'image/png' });

      const tempUrl = URL.createObjectURL(blob);

      return tempUrl
    },
    async handleModalConfirm (item, value) {
      uni.showLoading({ title: '删除中...', mask: true });
      try {

        if (!this?.formData?.id) {
          this.fileList.splice(value, 1)
          uni.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 500
          })

          return
        }

        let res = await apply.applyDeletePhoto({
          photo_id: item.source.id
        })

        if (res.status == 1) {
          uni.hideLoading();
          this.fileList.splice(value, 1)
          uni.showToast({
            title: res.msg || '删除成功',
            icon: 'success',
            duration: 500
          })
        } else {
          uni.hideLoading();
          uni.showToast({
            title: res.msg || '删除失败',
            icon: 'none',
            duration: 500
          })
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: error || '删除失败',
          icon: 'none',
          duration: 500
        })
      }
    },
    ImgviewClick,
    ProcessingURL,

  }
}
</script>

<style scoped>
.content {
  position: relative;
}

.upload-wrapper {
  display: flex;
  flex-direction: column;
}

.upload-btn-container {
  width: 150rpx;
  height: 150rpx;
  border: 1px dashed #ccc;
  border-radius: 8rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-btn-container:hover {
  border-color: #409eff;
}

.progress-container {
  margin-top: 20rpx;
  width: 100%;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background-color: #e4e7ed;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 24rpx;
  color: #606266;
  margin-top: 8rpx;
  text-align: center;
}

.file-list-container {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
  margin-top: 15rpx;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  width: 90vw;
}

.file-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.file-icon {
  margin-right: 15rpx;
}

.file-name {
  flex: 1;
  color: #333;
  font-size: 28rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.delete-btn {
  color: #fff;
  padding: 8rpx 20rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  margin-left: 20rpx;
  cursor: pointer;
}
</style>